import socket, sys, time
from threading import Thread

HOST = 'localhost'
PORT = 29093 # arbitrary port

class alive (Thread): # To let server know we are still running
    def __init__ (self, s):
        Thread.__init__ (self)
        self.s = s
        self.running = True
    def stop (self):
        self.running = False
    def run (self):
        while self.running:
            self.s.send ('Still running.')
            time.sleep (0.5)

class client:
    
    def run (self, c):
        time.sleep (5)

    def start (self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((HOST, PORT))
        except:
            print 'Could not find daemon. Is it running?'
            return

        s.send ('please') # ask nicely for a card
        card = s.recv(1024)

        try:
            c = int (card) # get an available card
        except ValueError:
            print 'Did not receive a card.'
            return

        a = alive (s)   # let daemon know we're still running
        a.start ()
        self.run (c)    # execute something
        a.stop ()

        s.send('done')  # all finished
        s.close ()
